<template>
  <div>
    <canvas @mousemove="handleMove" ref="webglcanvas"></canvas>
  </div>
</template>

<script>
  import * as Three from 'three';
  import earth from '../../assets/earth.jpg'

  export default {
    name: "three_1",
    data() {
      return {
        scene: '',
        camera: '',
        renderer: '',
        group: '',
        loader: '',
        mouseX: '',
        mouseY: ''
      }
    },
    mounted() {
      this.init();
      this.animate();
    },
    methods: {
      init() {
        this.scene = new Three.Scene();//创建场景
        this.camera = new Three.PerspectiveCamera(70, ((window.innerWidth - 400) / (window.innerHeight - 160)), 0.1, 2000);//创建相机
        this.camera.position.z = 500; //相机位置
        this.renderer = new Three.WebGLRenderer({
          canvas: this.$refs.webglcanvas,
          antialias: true,// true false表示是否开启反锯齿,
          alpha: false,// true false 表示是否可以设置背景色透明,
          precision: 'highp',// highp mediump lowp 表示着色精度选择,
          premultipliedAlpha: false,// true false 表示是否可以设置像素深度（用来度量图像的分辨率）,
          maxLights: 3,// 最大灯光数,
          stencil: false// false true 表示是否使用模板字体或图案
        });
        this.renderer.setSize(window.innerWidth - 400, window.innerHeight - 160);//设置渲染器尺寸
        this.group = new Three.Group();//创建组
        this.loader = new Three.TextureLoader();//创建材质加载器
        this.scene.add(this.group);//场景中加入组
        this.loader.load(earth, texture => {
          let geometry = new Three.SphereGeometry(200, 20, 20); //SphereGeometry创建球体
          let material = new Three.MeshBasicMaterial({map: texture}); //材质
          let mesh = new Three.Mesh(geometry, material);  //物体
          this.group.add(mesh);//向组中加入物体
        });
      },
      rotate() {
        this.camera.position.x += (this.mouseX - this.camera.position.x) * 0.05;
        this.camera.position.y += (this.mouseY - this.camera.position.y) * 0.05;
        // 拍摄角度， 可改变地球视角
        this.camera.lookAt(this.scene.position);
        this.group.rotation.y -= 0.005;//旋转速度
        this.renderer.render(this.scene, this.camera);//渲染器渲染场景
      },
      animate() {
        requestAnimationFrame(this.animate);
        this.rotate();
      },
      handleMove(ev) {
        this.mouseX = ev.clientX - (window.innerWidth - 400) / 2;
        this.mouseY = ev.clientY - (window.innerHeight - 160) / 2
      }
    }
  }
</script>

<style scoped>

</style>
